/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.manager.controler;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.asiainfo.ability.base.service.EsUtilsBean;
import org.asiainfo.ability.base.service.TraceService;
import org.asiainfo.ability.base.utils.JsonUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.gateway.model.Machine;
import org.asiainfo.ability.manager.vo.SearchCondition;
import org.aspectj.weaver.tools.Trace;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: visen
 * @Date: 2018/1/16
 * @Description:
 */
@RestController
public class LogControler {
    public static final Logger logger = LogManager.getLogger(LogControler.class);

    @Autowired
    private TraceService traceService;

    @RequestMapping(value = "/log/query", method = RequestMethod.POST)
    public @ResponseBody
    String queryLog(@RequestBody SearchCondition sc, HttpServletRequest request
            , HttpServletResponse response) throws Exception {
        Map conditions = new HashMap();
        if (!StringUtils.isBlank(sc.getTraceId())) {
            conditions.put("traceid", sc.getTraceId());
        }
        if (!StringUtils.isBlank(sc.getBizId())) {
            conditions.put("bizid", sc.getBizId());
        }
        boolean inSummary = false;
        if (!StringUtils.isBlank(sc.getReq())) {
            conditions.put("request", sc.getReq());
            inSummary = true;
        }

        if (!StringUtils.isBlank(sc.getResp())) {
            conditions.put("response", sc.getResp());
            inSummary = true;
        }

        if (!StringUtils.isBlank(sc.getTime())) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            Date time = sf.parse(sc.getTime());
            long begin = time.getTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(time);
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            String timeFiled = inSummary ? "time" : "begintime";
            long end = calendar.getTime().getTime();
            conditions.put(timeFiled, QueryBuilders
                    .rangeQuery(timeFiled)
                    .from(begin)
                    .to(end));
        }
        List<Map> result = null;
        List<String> fetchSources = new ArrayList();
        fetchSources.add("traceid");
        if (inSummary) {
            result = traceService.searchCalleeTrace(conditions, fetchSources
                    , null);
            if (!result.isEmpty()) {
                int i = 0;
                StringBuilder sb = new StringBuilder();
                for (Map item : result) {
                    sb.append(item.get("traceid")).append(" ");
                }
                sb.deleteCharAt(sb.length() - 1);
                conditions.clear();
                conditions.put("traceid", sb.toString());
            }
        }
        fetchSources.add("begindate");
        fetchSources.add("costtime");
        fetchSources.add("state");
        result =  traceService.getEsUtils().search("record_db", "record", conditions, null, null);

        /*
        if(!StringUtils.isBlank(this.traceId)) {
            conditions.put("traceid", this.traceId);
        }
        if(!StringUtils.isBlank(this.traceId)) {
            conditions.put("traceid", this.traceId);
        }
        */
        //List<Map> result = utilsBean.search("record_db", "record", conditions, null, null);
        for (Map data : result) {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            data.put("begintime", sf.format(new Date(((Long) data.get("begintime")).longValue())));
        }
        return JsonUtils.toJSON(result);
        //return "1";
    }


    private void setRet(HttpServletResponse response, String code) {
        try {
            response.getWriter().write(code);
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    public static void main(String[] args) throws Exception {

    }


}
